package com.kobeliu.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Set;
import java.util.TreeMap;

@Slf4j
public class SignUtil {

    public static String createSign(TreeMap<String, String> params,String merchantId) {

        String signValue = "";
        String stringSignTemp = "";
        String stringA = "";

        //获得stringA
        Set<String> keys = params.keySet();
        for (String key : keys) {
            stringA += (key + "=" + params.get(key) + "&");
        }
        stringA = stringA.substring(0, stringA.length() - 1);

        //获得stringSignTemp
        stringSignTemp = stringA + "&key=" + merchantId;

        //获得signValue
        signValue = encryptByMD5(stringSignTemp).toUpperCase();

        log.debug("预支付签名：" + signValue);
        return signValue;
    }

    public static String encryptByMD5(String sourceStr) {

        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes("UTF-8"));

            byte b[] = md.digest();
            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {

                i = b[offset];
                if (i < 0){
                    i += 256;
                }
                if (i < 16){
                    buf.append("0");
                    buf.append(Integer.toHexString(i));
                }
            }

            result = buf.toString();

        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        return result;


    }
}
